package com.webshop.servlet;

import com.webshop.Dao.PageDao;
import com.webshop.Dao.ProductDao;
import com.webshop.domain.Items;
import com.webshop.domain.user.User;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@WebServlet("/addItem")
public class addItem extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        Items item1 = new Items();
        try {
            String path = req.getServletContext().getRealPath("/img");
            List<FileItem> items = upload.parseRequest(req);
            String pname = items.get(0).getString("utf-8");
            String pprice = items.get(1).getString("utf-8");
            String sinfo = items.get(2).getString("utf-8");
            String pclass = items.get(3).getString("utf-8");
            String pinfo = items.get(4).getString("utf-8");
            item1.setPname(pname);
            item1.setPprice(Integer.parseInt(pprice));
            item1.setSinfo(sinfo);
            item1.setPclass(pclass);
            item1.setWhos(((User)req.getSession().getAttribute("user")).getUsername());
            FileItem item = items.get(5);
            String imgName = item.getName();
            imgName = imgName.substring(imgName.indexOf('.'));
            imgName = ProductDao.maxid()+imgName;
            String pimgsrc = "img/"+imgName;
            item1.setPimgsrc(pimgsrc);
            InputStream is = item.getInputStream();
            FileOutputStream fos = new FileOutputStream(new File(path+"/"+imgName));
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len=(is.read(buffer)))>-1){
                fos.write(buffer,0,len);
            }
            fos.close();
            is.close();
        } catch (FileUploadException ex) {
            ex.printStackTrace();
        }
        ProductDao.add(item1);
        resp.sendRedirect("index.jsp");
    }
}
